class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        if (headA == headB)
            return headA;
        int countA = 0;
        int countB = 0;
        ListNode* nodeA = headA;
        ListNode* nodeB = headB;
        while (nodeA)
        {
            nodeA = nodeA->next;
            countA++;
        }
        while (nodeB)
        {
            nodeB = nodeB->next;
            countB++;
        }
        ListNode* maxnode = headA;
        ListNode* minnode = headB;
        int step = countA - countB;
        if (countB > countA)
        {
            maxnode = headB;
            minnode = headA;
            step = countB - countA;
        }
        while (maxnode && step--)
            maxnode = maxnode->next;
        while (maxnode && minnode && maxnode != minnode)
        {
            maxnode = maxnode->next;
            minnode = minnode->next;
        }
        return maxnode;
    }
};